package com.team.mpc.config.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {



    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        ErrorMsg msg = new ErrorMsg();
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        if (e instanceof FlowException){
            msg.setMsg("限流了");
            msg.setStatus(100);
        }
        else if (e instanceof DegradeException){
            msg.setMsg("降级了");
            msg.setStatus(101);
        }
        else if (e instanceof ParamFlowException){
            msg.setMsg("热点参数限流了");
            msg.setStatus(102);
        }
        else if (e instanceof SystemBlockException){
            msg.setMsg("系统规则（负载/...不满足要求）");
            msg.setStatus(103);
        }
        else if (e instanceof AuthorityException){
            msg.setMsg("授权规则不通过");
            msg.setStatus(104);
        }
        httpServletResponse.getWriter().write(JSON.toJSONString(msg));
    }

    @Data
    class ErrorMsg{
        private Integer status;
        private String msg;
    }
}
